package com.example.glxt1.utils;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.server.HttpServerRequest;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
//import com.example.glxt1.entity.User;
//import com.example.glxt1.service.IUserService;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;


@Component
public class TokenUtil {
//    private  static  IUserService staticUserService;
//    @Resource
//    private  IUserService userService;

//    @PostConstruct
//    public  void  setUserService(){
//        staticUserService=userService;
//    }

    public static String genToken(String userId,String sign){
     return    JWT.create()
                // 添加payload
                .withAudience(userId)
                // 设置过期时间,2小时后过期
                .withExpiresAt(DateUtil.offsetHour(new Date(),2))
                // 设置password为签名 密钥
                .sign(Algorithm.HMAC256(sign));
    }
/***获取当前的用户信息
 * */
//    public static User getCurrentUser(){
//            try {
//                //            获取当前请求的request
//                HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//                String token=request.getHeader("token");
//                if(!StrUtil.isBlank(token)){
//                    String  userId= JWT.decode(token).getAudience().get(0);
//                    return  staticUserService.getById(Integer.parseInt(userId));
//                }
//            }catch (Exception e){
//                return null;
//
//            }
//            return null;
//    }
}
